#include <iostream>
#include "Worker.h"

using namespace std;

WorkerImp::WorkerImp(EventProcessor& _master, DistributedCounter& _dCounter)
: dCounter(_dCounter)
#ifdef DEBUG_EVPROC
: EventProcessorImp(true, "Worker") // comment to remove debug
#endif
{
  	Master.CopyFrom(_master);	
  	RegisterMessageProcessor(SearchMessage::type, &SearchThis, 1 /*priority*/);
  	RegisterMessageProcessor(DieMessage::type, &Die, 0 /*priority*/);
  	
	SendReady();	
}

void WorkerImp::SendReady(){

	EventProcessor myInterfClone;
	myInterfClone.CopyFrom(myInterface);

	ReadyMessage_Factory(Master, 0, myInterfClone);
}

void WorkerImp::FindTheString(string line, string search){

	size_t found = 0;
	int count = 0;
	while(found != string::npos){

		found = line.find(search,found);
		if(found != string::npos){
			++count;
			found += search.size();
		}
	}	
	EventProcessor myInterfClone;
	myInterfClone.CopyFrom(myInterface);
	DoneMessage_Factory(Master, count, myInterfClone);

}
MESSAGE_HANDLER_DEFINITION_BEGIN(WorkerImp, SearchThis, SearchMessage)  

	evProc.FindTheString(msg.line,msg.search);

MESSAGE_HANDLER_DEFINITION_END

MESSAGE_HANDLER_DEFINITION_BEGIN(WorkerImp, Die, DieMessage) 

		if(evProc.dCounter.Decrement(1) == 0){
			cout<<"I am the final Worker "<<endl;
			EventProcessor myInterfClone;
			myInterfClone.CopyFrom(evProc.myInterface);
			WorkerDoneMessage_Factory(evProc.Master, 0, myInterfClone);
		}
	evProc.EventProcessorImp::processDieMessage(evProc,msg);
MESSAGE_HANDLER_DEFINITION_END
